// https://bugs.llvm.org/show_bug.cgi?id=35729

#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>

void *
doAllocate(size_t size, size_t alignment)
{
    void *pOut;
    void *pBlock;

    pBlock = malloc(size + alignment - 1 + sizeof(ptrdiff_t));
    if (pBlock == NULL) {
        return NULL;
    }

    pOut = (void *)(
        (uintptr_t)((unsigned char *)pBlock + alignment - 1 + sizeof(ptrdiff_t))
        & ~(uintptr_t)(alignment - 1));

    /*
        Running scan-build outputs the following log:
        main.c:24:29: warning: Potential leak of memory pointed to by 'pBlock'
    */
    ((ptrdiff_t *)pOut)[-1] = (unsigned char*)pOut - (unsigned char*)pBlock;
    return pOut;
}

void
doFree(void *pMemory)
{
    free((void *)((unsigned char *)pMemory - ((ptrdiff_t *)pMemory)[-1]));
}

int
main(void)
{
    void *pMemory;

    pMemory = doAllocate(8, 256);
    doFree(pMemory);
    return 0;
}
